package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mydy.model.Advertisement;
import com.example.mydy.api.UserApi;
import com.example.mydy.model.AdvertisementResponse;
import com.example.mydy.model.AdvertisementListResponse;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AdvertisementActivity extends AppCompatActivity {

    private static final String TAG = "AdvertisementActivity";
    private static final String BASE_URL = "http://106.52.82.133:3000/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertisement);

        displayUserData();

        // 检查是否使用离线模式
        if (NetworkUtils.USE_OFFLINE_MODE) {
            loadMockAdvertisements();
        } else {
            loadOnlineAdvertisements();
        }

        setupNavigationBarClickListeners();
    }
    
    private void loadMockAdvertisements() {
        Log.d(TAG, "加载模拟广告数据");
        try {
            // 创建模拟广告数据
            List<Advertisement> advertisements = new ArrayList<>();
            
            Advertisement ad = new Advertisement();
            ad.setId(1);
            ad.setTitle("测试广告 - 离线模式");
            ad.setContent("这是一个测试广告内容。在离线模式下，您可以查看此测试广告。");
            ad.setImageUrl("https://via.placeholder.com/300");
            advertisements.add(ad);
            
            // 显示广告
            if (!advertisements.isEmpty()) {
                displayAdvertisement(advertisements.get(0));
            } else {
                Toast.makeText(this, "未获取到广告数据", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "加载模拟广告数据出错", e);
            Toast.makeText(this, "加载广告数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void loadOnlineAdvertisements() {
        Log.d(TAG, "从服务器加载广告数据");
        // 创建 Retrofit 实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 创建 UserApi 实例
        UserApi userApi = retrofit.create(UserApi.class);

        // 调用获取广告列表的接口
        Call<AdvertisementListResponse> call = userApi.getAdvertisements("Bearer " + UserManager.getInstance().getToken());
        call.enqueue(new Callback<AdvertisementListResponse>() {
            @Override
            public void onResponse(Call<AdvertisementListResponse> call, Response<AdvertisementListResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<Advertisement> advertisements = response.body().getAdvertisements();
                    if (advertisements != null && !advertisements.isEmpty()) {
                        displayAdvertisement(advertisements.get(0));
                    } else {
                        // 如果没有广告数据，提示用户
                        Toast.makeText(AdvertisementActivity.this, "未获取到广告数据", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // 请求失败，提示用户
                    Toast.makeText(AdvertisementActivity.this, "获取广告数据失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AdvertisementListResponse> call, Throwable t) {
                // 网络请求失败，提示用户并打印错误信息
                Toast.makeText(AdvertisementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                t.printStackTrace();
            }
        });
    }
    
    private void displayAdvertisement(Advertisement ad) {
        // 找到广告标题和内容的 TextView
        TextView adTitleTextView = findViewById(R.id.adv_title);
        TextView adContentTextView = findViewById(R.id.adv_description);
        ImageView adIconImageView = findViewById(R.id.adv_icon);
        
        // 设置广告标题和内容
        adTitleTextView.setText(ad.getTitle());
        adContentTextView.setText(ad.getContent());

        // 加载广告图片
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.ic_placeholder);
        requestOptions.error(R.drawable.ic_error);
        
        Glide.with(this)
            .load(ad.getImageUrl())
            .apply(requestOptions)
            .into(adIconImageView);

        // 设置查看详情按钮的点击事件
        findViewById(R.id.adv_link_button).setOnClickListener(v -> {
            // 跳转到广告文章内容界面
            Intent articleIntent = new Intent(this, AdvertisementArticleActivity.class);
            articleIntent.putExtra("articleTitle", ad.getTitle());
            articleIntent.putExtra("articleContent", ad.getContent());
            articleIntent.putExtra("articleImageUrl", ad.getImageUrl());
            startActivity(articleIntent);
        });
    }

    private void displayUserData() {
        // 获取共享偏好设置
        SharedPreferences sharedPreferences = getSharedPreferences("MyAppPrefs", MODE_PRIVATE);

        // 从共享偏好设置中获取用户数据
        int inviteCount = sharedPreferences.getInt("inviteCount", 0);
        double taskRewardToday = Double.parseDouble(sharedPreferences.getString("taskRewardToday", "0.0"));
        double subTaskReward = Double.parseDouble(sharedPreferences.getString("subTaskReward", "0.0"));
        double balance = Double.parseDouble(sharedPreferences.getString("balance", "0.0"));
        String userNickname = sharedPreferences.getString("userNickname", "");

        // 找到显示用户数据的 TextView
        TextView usernameTextView = findViewById(R.id.userNickname);
        TextView balanceTextView = findViewById(R.id.userBalance);
        TextView inviteCountTextView = findViewById(R.id.inviteCount);
        TextView taskRewardTodayTextView = findViewById(R.id.taskRewardToday);
        TextView subTaskRewardTextView = findViewById(R.id.subTaskReward);

        // 设置用户数据到 TextView
        usernameTextView.setText(userNickname);
        balanceTextView.setText(String.format("%.2f", balance));
        inviteCountTextView.setText(String.valueOf(inviteCount));
        taskRewardTodayTextView.setText(String.format("%.2f", taskRewardToday));
        subTaskRewardTextView.setText(String.format("%.2f", subTaskReward));
    }

    private void setupNavigationBarClickListeners() {
        // 设置导航栏点击事件
        findViewById(R.id.project_nav_home).setOnClickListener(v -> startActivity(new Intent(this, MainActivity.class)));
        findViewById(R.id.nav_advertisement).setOnClickListener(v -> {}); // 当前页面，无需操作
        findViewById(R.id.nav_project).setOnClickListener(v -> {
            try {
                startActivity(new Intent(this, ProjectActivity.class));
            } catch (Exception e) {
                Log.e("AdvertisementActivity", "无法启动ProjectActivity: " + e.getMessage());
                Toast.makeText(this, "正在加载项目页面...", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.nav_reward).setOnClickListener(v -> {
            try {
                startActivity(new Intent(this, RewardActivity.class));
            } catch (Exception e) {
                Log.e("AdvertisementActivity", "无法启动RewardActivity: " + e.getMessage());
                Toast.makeText(this, "正在加载悬赏页面...", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.nav_promotion).setOnClickListener(v -> {
            try {
                startActivity(new Intent(this, PromotionActivity.class));
            } catch (Exception e) {
                Log.e("AdvertisementActivity", "无法启动PromotionActivity: " + e.getMessage());
                Toast.makeText(this, "正在加载推广页面...", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.nav_my).setOnClickListener(v -> {
            try {
                startActivity(new Intent(this, MyActivity.class));
            } catch (Exception e) {
                Log.e("AdvertisementActivity", "无法启动MyActivity: " + e.getMessage());
                Toast.makeText(this, "正在加载我的页面...", Toast.LENGTH_SHORT).show();
            }
        });
    }
}